<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天窗口</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/blogList.css">
    <link rel="stylesheet" href="css/chat.css">

</head>
<body>
<!--    导航栏-->
<div class="nav">
    <img src="image/person_Blog.png" alt="">
    <span>我的博客系统</span>
    <div class="spacer">
        <a href="main.html" id="main">主页</a>
    </div>
</div>

<!--    页面版心-->
<div class="container">
    <!--        左侧个人信息-->
    <div class="left">
        <div class="card">
            <img id="photo">
            <h3 id="username"></h3>
        </div>
    </div>
    <!--        右侧内容    -->
    <div class="rightBody"></div>
</div>

<script src="jquery.js"></script>
<!--    得到当前用户的信息(左侧)   -->
<script src="js/common.js"></script>

<!--初始化聊天界面并得到双方的信息-->
<script>
    let myname = "";// 当前用户名
    let myimg = "";// 当前用户头像
    let yourname = "";// 对方名
    let yourimg = "";// 对方头像
    let myId = 0;
    let yourId = 0;
    let dialogBox = null;// 当前的对话框

    $.ajax({
        type: 'get',
        url: 'user',
        success: function (body) {
            myimg = './image/' + body.photo + '.png';
            myname = body.username
            myId = body.userId
        }
    })
    $.ajax({
        type: 'get',
        url: 'author'+location.search,
        contentType: 'application/json',
        dataType: 'json',
        success: function (body) {
            // 初始化对方名字和头像
            yourimg = './image/' + body.photo + '.png';
            yourname = body.username;
            yourId = body.userId;

            // 获取聊天窗口的左侧标题
            let right = document.querySelector(".rightBody");
            let theme = document.createElement("h2");
            theme.innerHTML = "与 " + body.username + " 的聊天窗口";
            right.appendChild(theme)
            let talk = document.createElement("div");
            talk.className = 'talk'

            // 对话框
            dialogBox = document.createElement("div");
            dialogBox.className = 'dialogBox'
            right.appendChild(dialogBox);
            // 输入框
            let input = document.createElement("textarea");
            input.className = 'textarea';
            input.maxLength = 500;
            input.placeholder = '按Enter发送消息 ( 最多500字 )'
            input.style = 'border: none; outline: none;width: 100%;' +
                'height: 30%;border-radius: 5px; padding: 0.5em 0.5em;font-size: 17px;'+
                'font-family: \'微软雅黑\'; resize: none';
            talk.appendChild(dialogBox);
            talk.appendChild(input)
            right.appendChild(talk)
            getUserMessage(body);
            getRight();

            $('.textarea').bind('keydown', function (e) {
                // enter键
                if(e.keyCode == 13){
                    let content = document.querySelector(".textarea");
                    let message = {
                        from: myId,
                        to: yourId,
                        content: content.value,
                        sendTime: getNowTime()
                    }
                    $.ajax({
                        type: 'post',
                        url: 'message'+location.search,
                        contentType: 'application/json',
                        data: JSON.stringify(message),
                        beforeSend: function(){
                            $('.textarea').val('')
                            websocket.send(JSON.stringify(message))
                        },
                        success: function () {
                            $('.textarea').val('')
                        }
                    })
                }
            })
        }
    })
</script>

<!--    获得当前会话窗口的所有消息   -->
<script>

    // 得到初始聊天界面
    getRight = function () {
        dialogBox = document.querySelector(".dialogBox");
        $.ajax({
            type: 'get',
            url: 'message'+location.search,
            dataType: 'json',
            success: function (body) {
                for (let every of body) {
                    appendMessage(every)
                }
                dialogBox.scrollTop = dialogBox.scrollHeight
            }
        })
    }

    appendMessage = function(every){
        let message = document.createElement('div');
        let img = document.createElement('img');

        let all = document.createElement('div')
        all.className = 'all';
        let top = document.createElement('div');
        top.className = 'top'
        img.className = 'img';
        let name = document.createElement('span');
        name.className = 'name';
        let time = document.createElement('span')
        time.className = 'time'
        let outContent = document.createElement('div');
        outContent.className = 'outContent'
        let content = document.createElement('div');
        content.className = 'content'

        let userId = every.from;
        // 是对方发来的消息
        if (userId == yourId){
            message.className = 'you';
            img.src = yourimg;
            name.innerHTML = yourname
        }else {
            message.className = 'me';
            img.src = myimg;
            name.innerHTML = myname
        }
        content.innerHTML = every.content;
        time.innerHTML = every.sendTime

        top.appendChild(name);
        top.appendChild(time);
        all.appendChild(top);
        outContent.appendChild(content)
        all.appendChild(outContent);

        // 挂载到上面
        if (message.className == 'you'){
            message.appendChild(img);
        }
        message.appendChild(all)
        if (message.className == 'me'){
            message.appendChild(img);
        }
        dialogBox.appendChild(message);
    }
    getNowTime = function() {
        var date = new Date();
        //年 getFullYear()：四位数字返回年份
        var year = date.getFullYear(); //getFullYear()代替getYear()
        //月 getMonth()：0 ~ 11
        var month = date.getMonth() + 1;
        //日 getDate()：(1 ~ 31)
        var day = date.getDate();
        //时 getHours()：(0 ~ 23)
        var hour = date.getHours();
        //分 getMinutes()： (0 ~ 59)
        var minute = date.getMinutes();
        //秒 getSeconds()：(0 ~ 59)
        var second = date.getSeconds();
        var time = year + '-' + this.addZero(month) + '-' + this.addZero(day) + ' ' + this.addZero(hour) + ':' + this.addZero(minute) + ':' + this.addZero(second);
        return time;
    }
    addZero = function(s) {
        return s < 10 ? ('0' + s) : s;
    }
</script>

<!--webSocket-->
<script>

    // 得到当前面对对象的 ID
    let authorId = location.search.split("=")[1];

    var websocket = null;
    if('WebSocket' in window){
        websocket = new WebSocket("ws://1.14.68.92:8080/blog/webSocket");
    }else{
        alert('该浏览器不支持!')
    }
    //连接成功建立的回调方法
    websocket.onopen = function(event){
        console.log('连接成功')
    }
    //接收到消息的回调方法
    websocket.onmessage = function(event){
        let message = event.data;
        message = JSON.parse(message)
        if (authorId == message.from || (myId == message.from)){
            appendMessage(message)
            dialogBox.scrollTop = dialogBox.scrollHeight
        }
    }
    //连接发生错误的回调方法
    websocket.onerror = function(){
        console.log('连接错误')
    };
    //监听窗口关闭事件，当窗口关闭时，主动去关闭 websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function(){
        console.log("连接关闭")
        websocket.close();
    }
    // 连接关闭的回调方法
    websocket.onclose = function(){
        console.log("连接关闭...")
    }
</script>
</body>
</html>